//
//  MKPictureView.swift
//  Weibo
//
//  Created by mac on 15/12/20.
//  Copyright © 2015年 MK. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

let cellID = "cellID"
let pictureMargin: CGFloat = 6

class MKPictureView: UICollectionView {
    
    var urlArr: [NSURL]? {
        didSet {
            testlabel.text = "\(self.urlArr?.count ?? 0)"
            
            //修改配图的尺寸
            let picSize = viewSize()
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(picSize)
            }
            
            //FIXME: - 刷新数据
            reloadData()
        }
    }
    
    //入口
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayout)
        flowLayout.minimumInteritemSpacing = pictureMargin
        flowLayout.minimumLineSpacing = pictureMargin
        
        self.registerClass(PictureCell.self, forCellWithReuseIdentifier: cellID)
        self.dataSource = self
        
        setUpSubViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpSubViews() {
        addSubview(testlabel)
        testlabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
    }
    
    //计算视图大小
    private func viewSize() ->CGSize {
        //配图的个数 和宽
        let itemNum = urlArr?.count ?? 0
        let maxWidth = screenSize.width - CGFloat(2 * cellIconMargin)
        let itemWidth = (maxWidth  - CGFloat(2 * pictureMargin)) / 3
        
        //FIXME: - 设置流水布局的itemSize
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        //无图
        if itemNum == 0 {
            return CGSizeZero
        }
        
        //1张
        if itemNum == 1 {
            let size = CGSize(width: 160, height: 120)
            layout.itemSize = size
            return size
        }
        
        //4张 2*2
        if itemNum == 4 {
            let width = itemWidth * 2 + pictureMargin
            return CGSizeMake(width, width)
        }
        
        //9张 (包括2，3，5，6，7，8，9张图片的个数)
        /* 九宫格
        1,2,3 ->1
        4,5,6 ->2
        7,8,9 ->3
        */
        
        //求行数
        let row = CGFloat((urlArr!.count - 1) / 3 + 1)
        return CGSize(width: maxWidth, height: row * itemWidth + (row - 1) * pictureMargin)
    }
    
    //加载子视图
    private lazy var testlabel: UILabel = UILabel(tText: "", tColor: UIColor.redColor(), tFont: 14, isNum: 1)
    
}

//实现数据源
extension MKPictureView: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urlArr?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellID, forIndexPath: indexPath) as! PictureCell
        cell.imageURL = urlArr![indexPath.item]
        //cell.backgroundColor = UIColor.randomColor()//随机颜色
        return cell
    }
}

//自定义item
class PictureCell: UICollectionViewCell {
    
    //获取image数据
    var imageURL: NSURL? {
        didSet {
            imView.sd_setImageWithURL(imageURL)
        }
    }
    
    //入口
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUpSubViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpSubViews() {
        contentView.addSubview(imView)
        imView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    //加载子视图
    private lazy var imView: UIImageView = {
        let images = UIImageView()
        //让图片正常化
        images.contentMode = UIViewContentMode.ScaleAspectFill
        images.clipsToBounds = true
        return images
        }()
}